const app = getApp();
import HttpRequst from '../../../utils/httpRequst.js'
import API from '../../../utils/config.js'
import SendFormId from '../../../utils/sendFormId.js'
Page({

  /**
   * 页面的初始数据
   * -1表示有审核失败   1表示都成功  -10表示图片待提交    0 (未上传)  -5上传失败   2 审核中
   */
  data: {
    info: "",
    infoCopy:"",
    zxqSrcStr: "",
    zxqIdStr: "",
    zxhSrcStr: "",
    zxhIdStr: "",
    isUp1: false,
    isUp2: false,
    zxqReason: "",
    zxhReason: "",
    fromwhere: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    this.setData({
      fromWhere: options.fromwhere ? options.fromwhere : ""
    });
    HttpRequst(false, API.houseimgs, 1, app.getUkey(), "", "POST", false, function(res) {

      that.setData({
        info: res.data,
        infoCopy: res.data,
        zxqSrcStr: that.getTotalSrc(res.data.zxq.lists),
        zxqIdStr: that.getTotalId(res.data.zxq.lists),
        zxqReason: that.getReason(res.data.zxq.lists),
        zxhSrcStr: that.getTotalSrc(res.data.zxh.lists),
        zxhIdStr: that.getTotalId(res.data.zxh.lists),
        zxhReason: that.getReason(res.data.zxh.lists),
      });

    });
  },

  goToHome: function() {
    wx.reLaunch({
      url: '/pages/index/index/index'
    });
  },

  //将src转成字符串
  getTotalSrc: function(data) {
    var str = [];
    if (data.length) {
      data.forEach(function(item, index, arr) {
        item.src && str.push(item.src);
      });
      return str.join("|");
    }
    return "";
  },
  //将id转成字符串
  getTotalId: function(data) {
    
    var str = [];
    if (data.length) {
      data.forEach(function(item, index, arr) {
        item.id !=="" && str.push(item.id);
      })
      return str.join("|");
    }
    return "";
  },
  //获取第1个表单是否可以提交表单状态***************
  getUp1Status: function() {
    var flag = false;
    if (this.data.info.sfz.status == -10) {
      flag = true;
    }
    this.data.info.zxq.lists.forEach(function(item, index, arr) {
      if (item.status == -10) {
        flag = true;
        return;
      }
    })
    return flag;
  },
  //获取第2个表单是否可以提交表单状态***************
  getUp2Status: function() {
    var flag = false;
    this.data.info.zxh.lists.forEach(function(item, index, arr) {
      if (item.status == -10) {
        flag = true;
        return;
      }
    })
    return flag;
  },


  //选择身份证照片*******************************************************************************
  chooseSfzImage: function() {
    var that = this;
    //已经上传 审核中  已完成  三种状态就要预览图片
    if (this.data.info.sfz.status >= 0 && !!this.data.info.sfz.src) {
      //预览照片
      wx.previewImage({
        current: this.data.info.sfz.full_src, // 当前显示图片的http链接
        urls: [this.data.info.sfz.full_src]
      });
    } else {
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function(res) {
          that.setData({
            ['info.sfz.full_src']: res.tempFilePaths[0],
            ['info.sfz.src']: res.tempFilePaths[0],
            ['info.sfz.reason']: false,
            ['info.sfz.status']: -10 //设置为-10表示图片上传等待表单提交
          });
          //上传图片
          that.uploadImg({
            path: [that.data.info.sfz],
            uploadType: "sfz"
          })
        }
      });
    }
  },
  //上传多张图片操作
  uploadImg: function(data) {
    wx.showLoading();
    var that = this,
      i = data.i ? data.i : 0, //当前上传的哪张图片
      success = data.success ? data.success : 0, //上传成功的个数
      fail = data.fail ? data.fail : 0; //上传失败的个数
    //不是最后一张的时候,且状态
    
    if (data.path[i].status != -10) {
      i++;
      data.i = i;
      that.uploadImg(data);
    } else {
      wx.uploadFile({
        // url: "https://wnworld.com/api/JiaJiaDai/upload.php",
        url: "https://api.haodian.cn/wxapp/jjd/jjd/upimg",
        
        filePath: data.path[i].src,
        name: 'img', //这里根据自己的实际情况改
        formData: {
          'ukey': app.getUkey()
        },
        success: (resp) => {
          success++; //图片上传成功，图片上传成功的变量+1
          resp.data = JSON.parse(resp.data);
          //上传成功的时候
          if (resp.data.status) {
            //身份证图片直接设置src就可以
            if (data.uploadType == "sfz") {
              that.setData({
                ['info.sfz.full_src']: resp.data.data.full_url,
                ['info.sfz.src']: resp.data.data.url,
                ['info.sfz.id']: that.data.info.sfz.id ? that.data.info.sfz.id : 0,
              });
            } else if (data.uploadType == "zxq") {
              //找到装修前的选项，进行设置
              var nameStr = 'info.zxq.lists[' + i + ']';

              that.setData({
                [nameStr + ".full_src"]: resp.data.data.full_url,
                [nameStr + ".id"]: that.data.info.zxq.lists[i].id ? that.data.info.zxq.lists[i].id : 0,
                [nameStr + ".src"]: resp.data.data.url,
              });


            } else if (data.uploadType == "zxh") {
              //如何找到
              var nameStr = 'info.zxh.lists[' + i + ']';
              that.setData({
                [nameStr + ".full_src"]: resp.data.data.full_url,
                [nameStr + ".id"]: that.data.info.zxh.lists[i].id ? that.data.info.zxh.lists[i].id : 0,
                [nameStr + ".src"]: resp.data.data.url,
              });
            }
          }else{
            //上传失败*************
            
            if (data.uploadType == "sfz") {
              that.setData({
                ['info.sfz.full_src']: data.path[i].src,
                ['info.sfz.src']: that.data.infoCopy.sfz.src ? that.data.infoCopy.sfz.src : "",
                ['info.sfz.id']: that.data.infoCopy.sfz.id ? that.data.infoCopy.sfz.id : "",
                ['info.sfz.status']:-5 //上传失败
              });
            } else if (data.uploadType == "zxq") {
              //如何找到
              var nameStr = 'info.zxq.lists[' + i + ']';

              that.setData({
                [nameStr + ".full_src"]:data.path[i].src,
                [nameStr+".status"]:-5,
                [nameStr + ".id"]:"",
                [nameStr + ".src"]:"",
              });


            } else if (data.uploadType == "zxh") {
              //如何找到
              var nameStr = 'info.zxh.lists[' + i + ']';
              that.setData({
                [nameStr + ".full_src"]: data.path[i].src,
                [nameStr + ".status"]:-5,
                [nameStr + ".id"]:"",
                [nameStr + ".src"]:"",
              });
            }
          }
        },
        fail: (res) => {
          fail++; //图片上传失败，图片上传失败的变量+1
          if (data.uploadType == "sfz") {
            that.setData({
              ['info.sfz.full_src']: data.path[i].src,
              ['info.sfz.src']: that.data.infoCopy.sfz.src ? that.data.infoCopy.sfz.src : "",
              ['info.sfz.id']: that.data.infoCopy.sfz.id ? that.data.infoCopy.sfz.id : "",
              ['info.sfz.status']: -5 //上传失败
            });
          } else if (data.uploadType == "zxq") {
            //如何找到
            var nameStr = 'info.zxq.lists[' + i + ']';

            that.setData({
              [nameStr + ".full_src"]: data.path[i].src,
              [nameStr + ".status"]: -5,
              [nameStr + ".id"]: "",
              [nameStr + ".src"]: "",
            });


          } else if (data.uploadType == "zxh") {
            //如何找到
            var nameStr = 'info.zxh.lists[' + i + ']';
            that.setData({
              [nameStr + ".full_src"]: data.path[i].src,
              [nameStr + ".status"]: -5,
              [nameStr + ".id"]: "",
              [nameStr + ".src"]: "",
            });
          }
        },
        complete: () => {
          i++; //这个图片执行完上传后，开始上传下一张

          if (i == data.path.length) {
            wx.hideLoading();
            if (data.uploadType == "zxq") {
              
              that.setData({
                zxqSrcStr: that.getTotalSrc(that.data.info.zxq.lists),
                zxqIdStr: that.getTotalId(that.data.info.zxq.lists)
              });

              
            } else if (data.uploadType == "zxh") {
              that.setData({
                zxhSrcStr: that.getTotalSrc(that.data.info.zxh.lists),
                zxhIdStr: that.getTotalId(that.data.info.zxh.lists)
              });
            }
            that.setData({
              isUp1: that.getUp1Status(),
              isUp2: that.getUp2Status()
            })

            
          } else {
            data.i = i;
            data.success = success;
            data.fail = fail;
            that.uploadImg(data);
          }
        }
      })
    }
  },
  //上传单张图片操作(其实就是重新上传)
  uploadImgSingle: function(data, index,isNew) {
    var that = this;
    wx.showLoading();
    wx.uploadFile({
      // url: "https://wnworld.com/api/JiaJiaDai/upload.php",
      url: "https://api.haodian.cn/wxapp/jjd/jjd/upimg",
      filePath: data.path.src,
      name: 'img', //这里根据自己的实际情况改
      formData: {
        'ukey': app.getUkey()
      },
      success: (resp) => {
        resp.data = JSON.parse(resp.data);
        if(resp.data.status){
          if (data.uploadType == "zxq") {
            var nameStr = 'info.zxq.lists[' + index + ']';
            that.setData({
              [nameStr + ".full_src"]: resp.data.data.full_url,
              [nameStr + ".id"]: that.data.info.zxq.lists[index].id ? that.data.info.zxq.lists[index].id : 0,
              [nameStr + ".src"]: resp.data.data.url,
              "zxqReason": that.getReason(that.data.info.zxq.lists)
            });

          } else if (data.uploadType == "zxh") {
            //如何找到
           
            var nameStr = 'info.zxh.lists[' + index + ']';
            that.setData({
              [nameStr + ".full_src"]: resp.data.data.full_url,
              [nameStr + ".id"]: that.data.info.zxh.lists[index].id ? that.data.info.zxh.lists[index].id : 0,
              [nameStr + ".src"]: resp.data.data.url,
              "zxhReason": that.getReason(that.data.info.zxh.lists)
            });
          }
        }else{
         
          if (data.uploadType == "zxq") {
            var nameStr = 'info.zxq.lists[' + index + ']';
            that.setData({
              [nameStr + ".full_src"]: data.path.src,
              [nameStr + ".id"]: isNew ? "" : that.data.infoCopy.zxq.lists[index].id,
              [nameStr + ".status"]: -5,
              [nameStr + ".src"]: isNew ? "" : that.data.infoCopy.zxq.lists[index].src,
              "zxqReason": that.getReason(that.data.info.zxq.lists)
            });

          } else if (data.uploadType == "zxh") {
            //如何找到
            
            var nameStr = 'info.zxh.lists[' + index + ']';
            that.setData({
              [nameStr + ".full_src"]: data.path.src,
              [nameStr + ".id"]: isNew ? "" : that.data.infoCopy.zxh.lists[index].id,
              [nameStr + ".status"]: -5,
              [nameStr + ".src"]: isNew ? "" : that.data.infoCopy.zxh.lists[index].src,
              "zxhReason": that.getReason(that.data.info.zxh.lists)
            });
          }
        }
        
      },
      fail: (res) => {
        if (data.uploadType == "zxq") {
          var nameStr = 'info.zxq.lists[' + index + ']';
          that.setData({
            [nameStr + ".full_src"]: data.path.src,
            [nameStr + ".id"]: isNew ? "" : that.data.infoCopy.zxq.lists[index].id,
            [nameStr + ".status"]: -5,
            [nameStr + ".src"]: isNew ? "" : that.data.infoCopy.zxq.lists[index].src,
            "zxqReason": that.getReason(that.data.info.zxq.lists)
          });

        } else if (data.uploadType == "zxh") {
          //如何找到

          var nameStr = 'info.zxh.lists[' + index + ']';
          that.setData({
            [nameStr + ".full_src"]: data.path.src,
            [nameStr + ".id"]: isNew ? "" : that.data.infoCopy.zxh.lists[index].id,
            [nameStr + ".status"]: -5,
            [nameStr + ".src"]: isNew ? "" : that.data.infoCopy.zxh.lists[index].src,
            "zxhReason": that.getReason(that.data.info.zxh.lists)
          });
        }
      },

      complete: () => {
        wx.hideLoading();
        if (data.uploadType == "zxq") {
          that.setData({
            zxqSrcStr: that.getTotalSrc(that.data.info.zxq.lists),
            zxqIdStr: that.getTotalId(that.data.info.zxq.lists)
          });
        } else if (data.uploadType == "zxh") {
          that.setData({
            zxhSrcStr: that.getTotalSrc(that.data.info.zxh.lists),
            zxhIdStr: that.getTotalId(that.data.info.zxh.lists)
          });
        }
        that.setData({
          isUp1: that.getUp1Status(),
          isUp2: that.getUp2Status()
        })
      }
    })
  },

  //未上传任何图片调用添加上传，可以添加多张
  chooseZxqImage: function () {
    var that = this;
    wx.chooseImage({
      count: 4, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {

        var resArr = [];
        res.tempFilePaths.forEach(function (item, index, arr) {
          resArr[index] = {};
          resArr[index].full_src = "";
          resArr[index].src = item;
          resArr[index].status = -10;
        })
        that.setData({
          ["info.zxq.lists"]: resArr
        });
        that.uploadImg({
          path: that.data.info.zxq.lists,
          uploadType: "zxq"
        })
      }
    });
  },
  //装修前    到底是预览还是上传图片************
  toggleZxqImage: function(e) {
    var that = this;
    var idx = e.currentTarget.dataset.idx;

    if ((this.data.info.zxq.lists[idx].status != -10 && this.data.info.zxq.lists[idx].status != -1 && this.data.info.zxq.lists[idx].status != -5) || this.data.info.zxq.status == 1) {

      wx.previewImage({
        current: this.data.info.zxq.lists[idx].full_src, // 当前显示图片的http链接
        urls: [this.data.info.zxq.lists[idx].full_src]
      })
    } else {

      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function(res) {
          var src = res.tempFilePaths[0]
          
          that.setData({
            ['info.zxq.lists[' + idx + '].full_src']: "",
            ['info.zxq.lists[' + idx + '].src']: src,
            
            ['info.zxq.lists[' + idx + '].status']: -10,
          });


          that.uploadImgSingle({
            path: that.data.info.zxq.lists[idx],
            uploadType: "zxq"
          }, idx, that.data.info.zxq.lists[idx].id == "" ? true : false)

        }
      });
    }
  },


  //已上传图片继续添加，可以添加1张
  addZxqImage: function() {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {

        
        var obj={
          full_src: res.tempFilePaths[0],
          src: res.tempFilePaths[0],
          id: 0,
          status: -10
        };
        that.setData({
          ['info.zxq.lists']:that.data.info.zxq.lists.concat(obj)

        });
        var len = that.data.info.zxq.lists.length
       
        that.uploadImgSingle({
          path: that.data.info.zxq.lists[len-1],
          uploadType: "zxq"
        }, len-1,true)
      }
    });
  },
  toggleZxhImage: function(e) {

    var that = this;
    var idx = e.currentTarget.dataset.idx;

    if ((this.data.info.zxh.lists[idx].status != -10 && this.data.info.zxh.lists[idx].status != -1 && this.data.info.zxh.lists[idx].status != -5) || this.data.info.zxh.status == 1) {

      wx.previewImage({
        current: this.data.info.zxh.lists[idx].full_src, // 当前显示图片的http链接
        urls: [this.data.info.zxh.lists[idx].full_src]
      })
    } else {
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function(res) {
          var src = res.tempFilePaths[0];
         

          that.setData({
            ['info.zxh.lists[' + idx + '].full_src']: "",
            ['info.zxh.lists[' + idx + '].src']: src,
            ['info.zxh.lists[' + idx + '].status']: -10
          });



        


          that.uploadImgSingle({
            path: that.data.info.zxh.lists[idx],
            uploadType: "zxh"
          }, idx, that.data.info.zxh.lists[idx].id == "" ? true : false)

        }
      });
    }
  },
  addZxhImage: function() {
    var that = this;

    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        var obj = {
          full_src: res.tempFilePaths[0],
          src: res.tempFilePaths[0],
          id:0,
          status: -10
        };
        that.setData({
          ['info.zxh.lists']: that.data.info.zxh.lists.concat(obj)

        });
        var len = that.data.info.zxh.lists.length
        
        that.uploadImgSingle({
          path: that.data.info.zxh.lists[len - 1],
          uploadType: "zxh"
        }, len - 1,true)
     
      }
    });
  },
  chooseZxhImage: function() {
    var that = this;
    wx.chooseImage({
      count: 4, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {

        var resArr = [];
        res.tempFilePaths.forEach(function(item, index, arr) {
          resArr[index] = {};
          resArr[index].full_src = "";
          resArr[index].src = item;
          resArr[index].status = -10;
        })
        that.setData({
          ["info.zxh.lists"]: resArr
        });
        that.uploadImg({
          path: that.data.info.zxh.lists,
          uploadType: "zxh"
        })
      }
    });
  },
  //获取原因
  getReason: function(data) {
    var arrCopy = [];
    if (data.length) {
      data.forEach(function(item, index, arr) {
        if (item.reason && item.status == -1) {
          arrCopy.push("图" + (index + 1) + "：" + item.reason)
        }
      })
    }

    return arrCopy.length ? arrCopy.join(";") : false;
  },
  //查看示例图片
  previewImage: function(e) {
    if (e.currentTarget.dataset.type == 0) {
      wx.previewImage({
        current: "https://api.haodian.cn/img/wechatapp/jjd/fwzp_sl_0.png", // 当前显示图片的http链接
        urls: ["https://api.haodian.cn/img/wechatapp/jjd/fwzp_sl_0.png"]
      })
    } else if (e.currentTarget.dataset.type == 1) {
      wx.previewImage({
        current: "https://api.haodian.cn/img/wechatapp/jjd/fwzp_sl_1.jpg", // 当前显示图片的http链接
        urls: ["https://api.haodian.cn/img/wechatapp/jjd/fwzp_sl_1.jpg"]
      })
    } else {
      wx.previewImage({
        current: "https://api.haodian.cn/img/wechatapp/jjd/fwzp_sl_2.jpg", // 当前显示图片的http链接
        urls: ["https://api.haodian.cn/img/wechatapp/jjd/fwzp_sl_2.jpg"]
      })
    }
  },


  formSubmit01: function(e) {
    var that = this;
    var arrCopy = [];
    app.getFormIds(e.detail.formId);
    SendFormId(app, "POST", 2, "");
    HttpRequst(true, API.saveimgs, 1, app.getUkey(), e.detail.value, "POST", false, function(res) {

      if (res.status == 1) {
        if (that.data.info.sfz.status == -10) {
          that.setData({
            ['info.sfz.status']: 2
          });
        }
        
        
        



        if (that.data.info.zxq.lists.length) {
          that.data.info.zxq.lists.forEach(function(item, index, arr) {
            if (item.status == -10) {
              that.setData({
                ["info.zxq.lists[" + index + "].status"]: 2
              });
            }

          })
        }

        that.setData({
          isUp1: that.getUp1Status()
        });
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 2000,
          success:function(){
            setTimeout(function(){
              wx.redirectTo({
                url:"/pages/index/uploadfwzp/uploadfwzp"
              })
            },1000)
          }
        });
        



      }


    });
  },

  formSubmit02: function(e) {
    var that = this;
    var arrCopy = [];
    app.getFormIds(e.detail.formId);
    SendFormId(app, "POST", 2, "");
    HttpRequst(true, API.saveimgs, 1, app.getUkey(), e.detail.value, "POST", false, function(res) {

      if (res.status == 1) {
        if (that.data.info.zxh.lists.length) {
          that.data.info.zxh.lists.forEach(function(item, index, arr) {
            if (item.status == -10) {
              that.setData({
                ["info.zxh.lists[" + index + "].status"]: 2
              });
            }
          })
        }
        that.setData({
          isUp2: that.getUp2Status()
        });

        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            setTimeout(function () {
              wx.redirectTo({
                url: "/pages/index/uploadfwzp/uploadfwzp"
              })
            }, 1000)
          }
        });



      }

    });
  },





})